﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SqliteORM;

namespace TwKarma.Data.Entity
{
	[Table]
	public class KarmaVote : TableBase
	{
        [PrimaryKey]
        public int ToId { get; set; }

        [PrimaryKey]
        public int FromId { get; set; }

		[Field]
		public long TweetStatusId { get; set; }

        /// <summary>
        /// this could be stored as a bit in the db to save space? probably not worth the hassle - John_Idol
        /// </summary>
		[Field]		
		public int Score { get; set; }

		[Field]
		public DateTime When { get; set; }

        /// <summary>
        /// Gets karma votes for a given user id
        /// </summary>
        /// <param name="toId">id of the user we are retrieving karma votes for</param>
        /// <returns>a list of karma votes for the given user id</returns>
        public static List<KarmaVote> GetKarmaVotesByToId(int toId)
        {
            var results = new List<KarmaVote>();

            using (TableAdapter<KarmaVote> adapter = TableAdapter<KarmaVote>.Open())
            {
                results = (List<KarmaVote>)adapter.ReadAll(Where.Equal("ToId", toId));
            }

            return results;
        }

        public static List<KarmaVote> GetKarmaVotesByToId(int toId, int page, int count)
        {
            return getKarmaVotes("WHERE ToId = " + toId, page, count);
        }

        public static List<KarmaVote> GetKarmaVotes(int page, int count)
        {
            return getKarmaVotes(string.Empty, page, count);
        }

        private static List<KarmaVote> getKarmaVotes(string where, int page, int count)
        {
            List<KarmaVote> votes = new List<KarmaVote>();

            using (DirtyBoy dirty = new DirtyBoy())
            {
                dirty.ExecuteNastyPureSql(
                    String.Format(
                    "SELECT ToId, FromId, TweetStatusId, Score, [When] " +
                    "FROM   KarmaVote " +
                    "{0} " +
					"ORDER BY [when] " +
                    "LIMIT  {1}, {2} ", where, (page - 1)* count, count),
                    row =>
                    {
                        votes.Add(new KarmaVote()
                            {
                                ToId = (int)row[0],
                                FromId = (int)row[1],
                                TweetStatusId = (long)row[2],
                                Score = (int)row[3],
                                When = (DateTime)row[4]
                            });
                        return true;
                    });                   
            }

            return votes;
        }		
	}
}